package com.cloud.school.bus.teacherhelper.modules.home;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.database.AllPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.database.TeacherPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.adapter.PictureSelectedAdapter;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoRequest;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoResponse;

/**
 * 相片选择界面 flag : 0表示所有照片，1表示相机拍摄
 * 
 * @author jiahongfei
 * 
 */
public class PictureSelectedActivity extends BaseActivity {

	private TitleNavBarView mTitleNavBarView;
	private GridView mGridView;
	private PictureSelectedAdapter mPictureSelectedAdapter;
	private ViewGroup mIgnoreLayout;
	private ViewGroup mNoDataLayout;

	private AllPictureIgnoreDB mAllPictureIgnoreDB;
	private TeacherPictureIgnoreDB mTeacherPictureIgnoreDB;
	private String mTitleString;
	private List<Picture> mPictures;
	private List<Picture> mPictureSelectedList = new ArrayList<Picture>();
	/** 0表示所有照片，1表示相机拍摄 */
	private int mFlag = 0;
	private int mCount = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_picture_selected);

		init();
	}

	@Override
	protected void init() {
		mFlag = getIntent().getIntExtra("flag", 0);
		mTitleString = getIntent().getStringExtra("title");
		mPictures = (List<Picture>) getIntent()
				.getSerializableExtra("Pictures");
		mCount = mPictures.size();
		if (1 == mFlag) {
			mTeacherPictureIgnoreDB = TeacherPictureIgnoreDB
					.getTeacherPictureIgnoreDB(mContext);
		}
		if (0 == mFlag) {
			mAllPictureIgnoreDB = AllPictureIgnoreDB
					.getAllPictureIgnoreDB(mContext);
		}
		
		mNoDataLayout = (ViewGroup)findViewById(R.id.noDataLayout);

		mIgnoreLayout = (ViewGroup) findViewById(R.id.ignoreLayout);

		mGridView = (GridView) findViewById(R.id.gridView);
		mPictureSelectedAdapter = new PictureSelectedAdapter(mContext,
				mPictures);
		mGridView.setAdapter(mPictureSelectedAdapter);
		
		if(0 == mPictures.size()){
			mNoDataLayout.setVisibility(View.VISIBLE);
			mGridView.setVisibility(View.GONE);
		}else {
			mNoDataLayout.setVisibility(View.GONE);
			mGridView.setVisibility(View.VISIBLE);
		}

		setTitleNavBar();
		setListener();
	}

	@Override
	protected void setListener() {

		Button ignoreButton = (Button) findViewById(R.id.ignoreButton);
		ignoreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showIgnoreDialog();

			}
		});

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				final ImageView selectImageView = (ImageView) arg1
						.findViewById(R.id.selectImageView);
				Picture picture = (Picture) mPictureSelectedAdapter
						.getItem(arg2);
				picture.isSelected = !picture.isSelected;
				if (picture.isSelected) {

					if (mPictureSelectedList.size() >= 9) {
						HandlerToastUI.getHandlerToastUI(mContext,
								getString(R.string.max_9_pictures));
						picture.isSelected = !picture.isSelected;
						return;
					}

					selectImageView.setVisibility(View.VISIBLE);
					mPictureSelectedList.add(picture);
				} else {
					selectImageView.setVisibility(View.GONE);
					mPictureSelectedList.remove(picture);
				}
				uploadIgnoreStatus();
			}
		});
		mGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Picture picture = (Picture) mPictureSelectedAdapter
						.getItem(arg2);
				HandlerToastUI.getHandlerToastUI(mContext, picture.toString());
				// DebugLog.logI("11111111111111111111 : " +
				// picture.toString());
				return false;
			}
		});
	}

	private void uploadIgnoreStatus() {
		mTitleNavBarView.setRightBubble(mPictureSelectedList.size() + "");
		if (mPictureSelectedList.size() > 0) {
			if (mIgnoreLayout.getVisibility() != View.VISIBLE) {
				mIgnoreLayout.setVisibility(View.VISIBLE);
			}
		} else {
			if (mIgnoreLayout.getVisibility() != View.GONE) {
				mIgnoreLayout.setVisibility(View.GONE);
			}
		}
	}

	@Override
	protected void setTitleNavBar() {
		mTitleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		mTitleNavBarView.setMessage(mTitleString);
		mTitleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回
				cancel();
			}
		});
		mTitleNavBarView.setRightButtonImageString(
				R.drawable.btn_title_upload_pic_xml, "", R.color.text_blue);
		mTitleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mPictureSelectedList.size() == 0) {
					showTipsDialog();
				} else {
					getClassinfo(new Runnable() {
						
						@Override
						public void run() {
							Intent intent = new Intent(mContext,
									SendFileToStuActivity.class);
							intent.putExtra("flag", mFlag);
							intent.putExtra("pictureList",
									(ArrayList<Picture>) mPictureSelectedList);
							// startActivity(intent);
							startActivityForResult(intent, 0);
						}
					});
					
				}
			}
		});
	}
	
	public void getClassinfo(final Runnable runnable) {
		if (null == mApplication.mClassInfo || null == mApplication.mTeacher
				|| null == mApplication.mStudentList) {
			NetworkClient.getNetworkClient().GetRequest(
					new GetClassinfoRequest(mContext), new GetClassinfoResponse() {
						@Override
						public void onResponse(
								ResponseHandlerInterface responseHandlerInterface) {

							if ("1".equals(code)) {
								mApplication.mClassInfo = classInfo;
								mApplication.mTeacher = teacher;
								mApplication.mStudentList = studentList;
								HandlerPostUI.getHandlerPostUI(runnable);
							} else if ("-4".equals(code)) {
								// HandlerToastUI.getHandlerToastUI(
								// SlidingActivity.this, "不存在班级");
							}
						}
					});
		} else {
			HandlerPostUI.getHandlerPostUI(runnable);
		}
	}

	private void showTipsDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage(mContext.getString(R.string.tips),
				Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.please_select_picture));
		customAlertDialog.setLeftButton(mContext.getString(R.string.confirm),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	private void showIgnoreDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage(getString(R.string.ignore),
				Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.choose_ignore));
		customAlertDialog.setLeftButton(getString(R.string.yes),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						ignorePicture();
					}
				});
		customAlertDialog.setRightButton(getString(R.string.no),
				new OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				});
		customAlertDialog.show();
	}

	private void ignorePicture() {
		if (0 == mFlag) {
			mAllPictureIgnoreDB.putInsert(mPictureSelectedList);
		} else if (1 == mFlag) {
			mTeacherPictureIgnoreDB.putInsert(mPictureSelectedList);
		}
		mPictures.removeAll(mPictureSelectedList);
		mPictureSelectedList.clear();
		mPictureSelectedAdapter.notifyDataSetChanged();
		uploadIgnoreStatus();
		
		if(0 == mPictures.size()){
			mNoDataLayout.setVisibility(View.VISIBLE);
			mGridView.setVisibility(View.GONE);
		}else {
			mNoDataLayout.setVisibility(View.GONE);
			mGridView.setVisibility(View.VISIBLE);
		}
	}

	private void cancel() {
		if (mCount != mPictures.size()) {
			Intent intent = new Intent();
			intent.putExtra("pictureList", (ArrayList<Picture>) mPictures);
			intent.putExtra("flag", mFlag);
			setResult(RESULT_OK, intent);
		}
		finish();
		
		ImageLoader.getInstance().clearMemoryCache();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 上传图片界面返回
			switch (resultCode) {
			case RESULT_OK: {
				ignorePicture();
				showUploadHandlerSucceed();
				mPictureSelectedAdapter.clearAllSelected();
				mPictureSelectedAdapter.notifyDataSetChanged();
				break;
			}
			case RESULT_CANCELED: {
				mPictureSelectedList.clear();
				mPictureSelectedAdapter.clearAllSelected();
				mPictureSelectedAdapter.notifyDataSetChanged();
				uploadIgnoreStatus();
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 显示图片上传处理成功的对话框，但是上传成功或者是不成功需要去上传列表中看，这里只是个提示
	 */
	private void showUploadHandlerSucceed() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog
				.setMessage(getString(R.string.uploading_progress_check_the_details_by_tapping_left_side_menu));
		customAlertDialog.setLeftButton(getString(R.string.confirm),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			cancel();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
